package cn.iocoder.yudao.module.crm.service.billaccount;

import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.crm.controller.admin.billaccount.vo.BillAccountPageReqVO;
import cn.iocoder.yudao.module.crm.controller.admin.billaccount.vo.BillAccountSaveReqVO;
import cn.iocoder.yudao.module.crm.dal.dataobject.billaccount.BillAccountDO;
import cn.iocoder.yudao.module.crm.dal.mysql.billaccount.BillAccountMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;


/**
 * 收款账号管理 Service 实现类
 *
 * @author nail.zhang
 */
@Service
@Validated
public class BillAccountServiceImpl implements BillAccountService {

    @Resource
    private BillAccountMapper billAccountMapper;

    @Override
    public Long createBillAccount(BillAccountSaveReqVO createReqVO) {
        // 插入
        BillAccountDO billAccount = BeanUtils.toBean(createReqVO, BillAccountDO.class);
        billAccountMapper.insert(billAccount);
        // 返回
        return billAccount.getId();
    }

    @Override
    public void updateBillAccount(BillAccountSaveReqVO updateReqVO) {
        // 校验存在
        validateBillAccountExists(updateReqVO.getId());
        // 更新
        BillAccountDO updateObj = BeanUtils.toBean(updateReqVO, BillAccountDO.class);
        billAccountMapper.updateById(updateObj);
    }

    @Override
    public void deleteBillAccount(Long id) {
        // 校验存在
        validateBillAccountExists(id);
        // 删除
        billAccountMapper.deleteById(id);
    }

    private void validateBillAccountExists(Long id) {
        if (billAccountMapper.selectById(id) == null) {
            //throw exception(BILL_ACCOUNT_NOT_EXISTS);
        }
    }

    @Override
    public BillAccountDO getBillAccount(Long id) {
        return billAccountMapper.selectById(id);
    }

    @Override
    public PageResult<BillAccountDO> getBillAccountPage(BillAccountPageReqVO pageReqVO) {
        return billAccountMapper.selectPage(pageReqVO);
    }

    @Override
    public BillAccountDO getDefaultBillAccount() {

        List<BillAccountDO> list = billAccountMapper.selectList(BillAccountDO::getDefaultFlag,1);
        if(CollectionUtil.isNotEmpty(list)){
            return list.get(0);
        }
        list = billAccountMapper.selectList();

        if(CollectionUtil.isNotEmpty(list)){
            return list.get(0);
        }

        return null;
    }

}
